The catch
block of a checked exception "E" may be hidden because the corresponding try
block only throws exceptions
derived from E.
These derived exceptions are handled in dedicated catch
blocks prior to the catch
block of the base exception E.
The catch
block of E is unreachable and should be considered dead code. It should be removed, or the entire try-catch structure should
be refactored.
It is also possible that a single exception type in a multi-catch block may be hidden while the catch block itself is still reachable. In that case
it is enough to only remove the hidden exception type or to replace it with another type.
Noncompliant code example
public class HiddenCatchBlock {
public static class CustomException extends Exception {
}
public static class CustomDerivedException extends CustomException {
}
public static void main(String[] args) {
try {
throwCustomDerivedException();
} catch(CustomDerivedException e) {
// ...
} catch(CustomException e) { // Noncompliant; this code is unreachable
// ...
}
}
private static void throwCustomDerivedException() throws CustomDerivedException {
throw new CustomDerivedException();
}
}
Compliant solution
public class HiddenCatchBlock {
public static class CustomException extends Exception {
}
public static class CustomDerivedException extends CustomException {
}
public static void main(String[] args) {
try {
throwCustomDerivedException();
} catch(CustomDerivedException e) { // Compliant; try-catch block is "catching" only the Exception that can be thrown in the "try"
//...
}
}
}